package cn.edu.scut.sys.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.springframework.stereotype.Component;
import cn.edu.scut.sys.dao.DepartmentDao;
import cn.edu.scut.sys.utils.StringUtils;
import cn.edu.scut.sys.vo.Department;

@Component("departmentDao")
public class DepartmentDaoImpl implements DepartmentDao{

	private SessionFactory sessionFactory;

	@Resource(name="sessionFactory")
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Override
	public Long count() {
		String hql = "select count(id) from Department";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		return Long.valueOf(query.uniqueResult().toString());
	}

	@Override
	public List<Department> list(int start, int limit, String sort, String sidx) {
		
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Department.class);
		criteria.setFirstResult(start).setMaxResults(limit);
		if (!StringUtils.isEmpty(sort) && !StringUtils.isEmpty(sidx)){
			if ("desc".equals(sort)){
				criteria.addOrder(Order.desc(sidx));
			} else if ("asc".equals(sort)){
				criteria.addOrder(Order.asc(sidx));
			}
		}
		
		return criteria.list(); 
		}

	@Override
	public void insert(Department department) {
		sessionFactory.getCurrentSession().save(department);
		sessionFactory.getCurrentSession().flush();
		sessionFactory.getCurrentSession().clear();
	}
	
	@Override
	public Department getDepartment(String id){
		
		String hql = "from Department u where u.id=?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setString(0, id);
		return (Department)query.uniqueResult();
	}
	
	@Override
	public boolean delDepartment(int id) {

		String hql = "delete Department u where u.id = ?";
		Query query = sessionFactory.getCurrentSession().createQuery(hql);
		query.setInteger(0, id);
 
		return (query.executeUpdate() > 0);
	}
	
	@Override
	public boolean updateDepartment(Department department) {
		try {
			
			sessionFactory.getCurrentSession().update(department);
			sessionFactory.getCurrentSession().flush();
			sessionFactory.getCurrentSession().clear();
			
			return true;
			
		} catch (HibernateException e) {
			return false;
		}
	}

	@Override
	public List<Department> listAll() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(Department.class);
		return criteria.list();
	}
	
}
